package com.ruoyi.act.config.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.AbstractRequestLoggingFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "traceLogFilter", urlPatterns = "{/api*}")
@Component
public class TraceLogFilter extends AbstractRequestLoggingFilter {

    private static final Logger logger = LoggerFactory.getLogger(TraceLogFilter.class);

    private final String TRACE_ID = "requestId";// 线程追踪ID

    private final String BEGIN_TIME_MILLIS = "BEGIN_TIME_MILLIS";// 开始时间

    @Override
    protected void beforeRequest(HttpServletRequest httpServletRequest, String s) {
        MDC.put(TRACE_ID, UUID.randomUUID().toString().replaceAll("-", ""));
        MDC.put(BEGIN_TIME_MILLIS, String.valueOf(System.currentTimeMillis()));

    }

    @Override
    protected void afterRequest(HttpServletRequest httpServletRequest, String s) {
        logger.info("接口信息{} 耗费时间{}ms", s, (System.currentTimeMillis() - Long.parseLong(MDC.get(BEGIN_TIME_MILLIS))));
    }

    @Override
    public void destroy() {
        MDC.remove(TRACE_ID);
    }

    @Override
    protected boolean isIncludePayload() {
        return true;
    }

    @Override
    protected boolean isIncludeQueryString() {
        return true;
    }

}
